package EGS.impl;
import java.util.Vector;
import java.util.concurrent.ExecutorService;

import javax.swing.JTable;

import org.dom4j.Document;
import org.dom4j.Element;

import com.google.gson.Gson;

import LOGISTICS.c_material;
import LOGISTICS.m_material;
import TOOLS.SQLtool;
import TOOLS.errCodeManagement;
import WORKPLACE.URLapi;
import WORKPLACE.stationClient;

public class EGS_execute_service520Impl{
	public boolean isUnknowCase = false;
	ExecutorService iExecutorService;
	Document MSG;
	boolean isPanel = false;
	stationClient iClient=null;
	SQLtool sql = null;
	/**
	 * 520 物料装载_备料_必须有台车元素
	 */
	public EGS_execute_service520Impl(stationClient nClient, Document MSG_in, ExecutorService executorService, 
			SQLtool goldenSql) throws Exception {
		super();
		sql=goldenSql;
		if(nClient!=null) {
			iClient=nClient;
		}else {
			iClient=null;
		}
		MSG = MSG_in;
		iExecutorService = executorService;
	}

	public Document runCal() {
		String msgClass = "";
		try {
			if (MSG == null) {
				return null;
			}
			Element Mroot = MSG.getRootElement();
			msgClass = Mroot.element("header").attribute("messageClass").getValue();
			String transactionID = Mroot.element("header").attribute("transactionID").getValue();
			String iStation;

			iStation = Mroot.element("header").element("location").attribute("equipmentName").getValue();

			if (msgClass.equals("520")) {// 520 物料装载_备料_必须有台车元素
				String str = Mroot.element("body").element("operation").attribute("type").getValue();
				if (str.length() < 1) {
					str = "1";
				}
				String isReplace = str;
				String op = Mroot.element("body").element("operation").attribute("operator").getValue();
				String time = Mroot.element("body").element("operation").attribute("timestamp").getValue();
				String cartID = "";
				try {
					cartID = Mroot.element("body").element("cart").attribute("ID").getValue();
				} catch (Exception e3) {
					;
				}
				if (cartID == null || cartID.length() < 1) {
					cartID = "NA";
				}
				String iMaterialID = Mroot.element("body").element("material").attribute("id").getValue();
				String pos = Mroot.element("body").element("position").attribute("p1").getValue();
				String p1 = "-1", p2 = "-1", p3 = "-1";
				try {
					p1 = Mroot.element("body").element("position").attribute("p2").getValue();
				} catch (Exception e) {
					;
				}
				try {
					p2 = Mroot.element("body").element("position").attribute("p3").getValue();
				} catch (Exception e) {
					;
				}
				try {
					p3 = Mroot.element("body").element("position").attribute("p4").getValue();
				} catch (Exception e) {
					;
				}
				try {
					str = Mroot.element("body").element("position").attribute("feederID").getValue();
					if (str == null || str.length() < 1) {
						str = "-1";
					}
				} catch (Exception e) {
					str = "-1";
				}
				String feeder = str;

				Mroot.remove(Mroot.element("body"));
				Element eleB = Mroot.addElement("body");
				Element eleR = eleB.addElement("result");
				String iiMaterialID = iMaterialID;// 电文里申请安装的料
				String soMaterialID = null;// 设备当前已安装的料
				/**
				 *  设备当前已安装的料
				 */
				String sMaterialID = null;// 设备当前已安装的料
				m_material nReel = null;// 设备当前已安装的料的最后序的料
				try {

					Vector<String> runningReels = new Vector<String>();
					c_material cm = new c_material(sql);
					if (isReplace.equals("2")) {// 如果要接料，先查当前料
						str = "select reel from setupLocation " + "where station='" + iStation + "' and location='"
								+ pos + "' and p1='" + p1 + "' and p2='" + p2 + "' and p3='" + p3 + "'";
						JTable tt = sql.select(str);
						if (tt != null && tt.getRowCount() > 0) {
							soMaterialID = (String) tt.getValueAt(0, 0);
							sMaterialID = soMaterialID;
							if (sMaterialID != null && sMaterialID.length() > 0) {
								nReel = cm.getMaterial(sMaterialID);
								runningReels.add(sMaterialID);
								while (nReel.nextReel.length() > 0) {
									try {
										if (runningReels.indexOf(nReel.nextReel) < 0) {
											runningReels.add(nReel.nextReel);
											nReel = new c_material(sql).getMaterial(nReel.nextReel);
										} else {
											nReel.nextReel = "";
										}
									} catch (Exception e3) {
										nReel.nextReel = "";
									}
								}
								sMaterialID = nReel.materialID;
								if(runningReels.indexOf(iiMaterialID)>=0) {
									throw new Exception("禁止重复接料");
								}
							} else {
								isReplace = "1";
							}
						} else {
							isReplace = "1";
						}
					}

					// 查询料盘信息，位置、数量、接料
					m_material iReel = cm.getMaterial(iMaterialID);
					if (iReel.quantity < 1) {
						throw new Exception("-179");
					}
					if(iReel.location!=null && iReel.location.equals("WMS")) {
						throw new Exception("-185");//该物料已退库未领料
					}
					int preC = 0;
					Vector<String> setupReels = new Vector<String>();
					setupReels.add(iMaterialID);
					m_material rrc=null;
					while (iReel.preReel.length() > 0) {
						try {
							if (setupReels.indexOf(iReel.preReel) < 0) {
								rrc=iReel;
								iReel = new c_material(sql).getMaterial(iReel.preReel);
								if(iReel.quantity>0) {
									setupReels.add(iReel.materialID);
									preC += 1;
								}else {
									iReel=rrc;
									iReel.preReel = "";
								}
								
							} else {
								iReel.preReel = "";
							}
						} catch (Exception e3) {
							iReel.preReel = "";
						}
					}
					str = "";
					if (!iReel.materialID.equals(iMaterialID)) {
						str = "扫描Reel:" + iMaterialID + "带出的第" + preC + "前序物料";
					}
					if (!iReel.materialID.equals(sMaterialID)) {
						String tips = str;
						String iisReplace = isReplace;
						String ssMaterialID = sMaterialID;
						String icartID = cartID;
						m_material ioReel = iReel;
						Thread iTH = new Thread(new Runnable() {
							int istate = Integer.parseInt(iisReplace);
							String iOP = op;
							String iTime = time;
							m_material iiReel = ioReel;
							String oMaterial = iiMaterialID;
							String sMaterial = ssMaterialID;
							String iiStation = iStation;
							String iicartID = icartID;
							String iLocation = pos;
							String iFeeder = feeder;
							String iTips = tips;
							@Override
							public void run() {
								try {
									String mlocation = iiStation + "@" + iicartID + "@" + iLocation;
									c_material cmt = new c_material(sql);
									try {
										String oOrder=getStationOrder(iiStation);
										cmt.logMaterial(istate, iOP, iTime, iiReel.materialID, iiReel.quantity,
												iiStation, iicartID + "@" + iLocation, iFeeder, iTips,oOrder);
										if (istate == 2) {// 接料
											String str = "update materialID set preReel='" + sMaterial
													+ "' where materialID='" + iiReel.materialID + "'";
											sql.Command(str);
											str = "update materialID set nextReel='" + iiReel.materialID
													+ "' where materialID='" + sMaterial + "'";
											sql.Command(str);
										}
										if(!iiReel.location.equals(mlocation)) {//增加API登记
											sql.Command("update materialID set location='lineBIN' " + "where location='"
													+ mlocation + "'");
											sql.Command("update materialID set location='" + mlocation
													+ "' where materialID='" + oMaterial + "'");
											updateLocation(oMaterial,mlocation);
										}
									} catch (Exception e3) {
//										String str=errCodeManagement.getErrText(e3.getMessage());
										;
									}
								} catch (Exception e2) {
//									String str=errCodeManagement.getErrText(e2.getMessage());
									;
								}
							}
						});

						//  检查feeder是否处在空闲位置，待开发

						if (isReplace.equals("1")) {// 换料
							str = "update setupLocation set cartID='" + cartID + "' ,feeder='" + feeder + "',reel='"
									+ iReel.materialID + "',nextReel='" + iReel.nextReel + "',quantity="
									+ iReel.quantity + ",lastEdit=GETDATE() " + "where station='" + iStation
									+ "' and location='" + pos + "' and p1='" + p1 + "' and p2='" + p2 + "' and p3='"
									+ p3 + "'";
							try {
								sql.Update(str);
							} catch (Exception e3) {
								if (e3.getMessage().equals("-116")) {
									str = "insert setupLocation (station,cartID,location,p1,p2,p3,feeder,reel,nextReel,quantity) values "
											+ "('" + iStation + "','" + cartID + "','" + pos + "','" + p1 + "','" + p2
											+ "','" + p3 + "','" + feeder + "','" + iReel.materialID + "','"
											+ iReel.nextReel + "'," + iReel.quantity + ")";
									sql.Command(str);
								} else {
									throw e3;
								}
							} // 更新物料所在位置、feeder所在位置
						} else if (isReplace.equals("2")) {
							if (!iReel.partType.part.partNumber.equals(nReel.partType.part.partNumber)) {
								throw new Exception("-178");
							}
							if (sMaterialID.equals(soMaterialID)) {
								sql.Command("update setupLocation set nextReel='" + iReel.materialID
										+ "',lastEdit=getDate() where reel='" + sMaterialID + "'");
							}
						}
						iTH.start();

					} else {
						if (isReplace.equals("2")) {
							throw new Exception("-182");
						}
					}

					eleR.addAttribute("errorCode", "0");
					eleR.addAttribute("errorText", "Valid");
					eleR.addAttribute("actionCode", "0");
					AKSLogs(5201, "" + iiMaterialID + "_" + cartID + "_" + iStation);
				} catch (Exception e) {
					str = errCodeManagement.getErrText(e.getMessage());
					eleR.addAttribute("errorCode", "1");
					eleR.addAttribute("errorText", str);
					eleR.addAttribute("actionCode", transactionID);
					AKSLogs(5200, "" + iiMaterialID + "_" + cartID + "_" + iStation + "_" + str);
				}
			} else {
				isUnknowCase = true;
				return null;
			}
			return MSG;
		} catch (Exception e) {
			if(iClient==null) {
				Element Mroot = MSG.getRootElement();
				Element eleR = Mroot.element("body").addElement("result");
				eleR.addAttribute("errorCode", "1");
				eleR.addAttribute("errorText", "工位信息获取失败");
				eleR.addAttribute("actionCode", "0");
				return MSG;
			}
			String str = errCodeManagement.getErrText(e.getMessage());
			System.out.println(str);
			return null;
		}

	}
	
	public void updateLocation(String materialID,String location) {
		URLapi aa=new URLapi();//将501作为有板监控
		aa.RESTInvoker("http://192.168.0.220:8081", "","");
		String ijson=new Gson().toJson(location);
		aa.putDataToServer("/api/materialLogistics/material/locationOff", ijson);
		Location4material poster=new Location4material();
		poster.setRid(materialID);
		poster.setLocation(location);
		ijson=new Gson().toJson(poster);
		aa.putDataToServer("/api/materialLogistics/material/location", ijson);
	}

	public void AKSLogs(int iType, String ilogClientNews) {
		SQLtool.AKSLogs(iType, ilogClientNews);
	}
	
	private String getStationOrder(String iStation) throws Exception {
		if(iStation.endsWith("NPM-M2")) {// 应对M2不激活工单的特殊设定
			iStation=iStation.replaceAll("-M2", "-M1");
		}
		String str="select orderNumber from assetStation where ID='"+iStation+"'";
		JTable t=sql.select(str);
		String oOrder="";
		if(t!=null && t.getRowCount()>0) {
			oOrder=""+t.getValueAt(0, 0);
		}else {
			if(iStation.endsWith("M2")) {// 应对M2不激活工单的特殊设定
				iStation=iStation.replaceAll("-M2", "-M1");
			}
			str="select orderNumber from assetStation where ID='"+iStation+"'";
			t=sql.select(str);
			if(t!=null && t.getRowCount()>0) {
				oOrder=""+t.getValueAt(0, 0);
			}
		}
		return oOrder;
	}

}
